package com.zsh.wanandroid.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;

import com.dxq.basic_ui_library.loadSirCallBack.EmptyCallback;
import com.dxq.basic_ui_library.loadSirCallBack.ErrorCallback;
import com.dxq.basic_ui_library.loadSirCallBack.LoadingCallback;
import com.zsh.wanandroid.R;
import com.zsh.wanandroid.api.ApiService;
import com.zsh.wanandroid.base.BaseFragment;
import com.zsh.wanandroid.base.BasePagerFragment;
import com.zsh.wanandroid.bean.BaseResult;
import com.zsh.wanandroid.bean.ProjectTreeBean;
import com.zsh.wanandroid.http.ApiRequest;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author zsh
 * @date 2020/3/12.
 * 功能：项目fragment
 */

public class ProjectFragment extends BaseFragment {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    private SparseArray<ProjectPagerFragment> tabFragmentSparseArray = new SparseArray<>();

    //创建ProjectFragment
    public static ProjectFragment newInstance(Bundle bundle) {
        ProjectFragment fragment = new ProjectFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (null != arguments) {

        }
    }

    @Override
    protected int onCreateFragmentView() {
        return R.layout.fragment_common_tab;
    }

    @Override
    protected void initView(View view) {
        tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
    }

    /**
     * 获取接口数据
     */
    @Override
    protected void loadNet() {
        getTabLayoutData();
    }

    @Override
    protected void onNetReload(View v) {
        mBaseLoadService.showCallback(LoadingCallback.class);
        loadNet();
    }

    /**
     * 接口获取项目分类
     */
    private void getTabLayoutData() {
        ApiService apiService = ApiRequest.getInstance(getContext()).create(ApiService.class);
        apiService.getProjectTree().enqueue(new Callback<BaseResult<List<ProjectTreeBean>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<ProjectTreeBean>>> call,
                                   Response<BaseResult<List<ProjectTreeBean>>> response) {
                BaseResult<List<ProjectTreeBean>> body = response.body();
                if (null == body) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                    return;
                }
                List<ProjectTreeBean> data = body.getData();
                if (null == data) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                    return;
                }
                mBaseLoadService.showSuccess();
                //初始化设置tabLayout
                initTabLayout(data);
            }

            @Override
            public void onFailure(Call<BaseResult<List<ProjectTreeBean>>> call, Throwable t) {
                mBaseLoadService.showCallback(ErrorCallback.class);
            }
        });
    }

    private void initTabLayout(List<ProjectTreeBean> data) {
        for (int i = 0; i < data.size(); i++) {
            tabLayout.addTab(tabLayout.newTab().setText(data.get(i).getName()));
        }

        initViewPager(data);

        //tabLayout监听事件
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //添加选中Tab的逻辑
                viewPager.setCurrentItem(tab.getPosition(), false);//改变viewpager
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次选中tab的逻辑
            }
        });
    }

    private void initViewPager(final List<ProjectTreeBean> data) {
        //viewPager设置adapter当fragment嵌套fragment时，必须使用getChildFragmentManager()
        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                Bundle bundle = new Bundle();
                bundle.putInt("cid", data.get(position).getId());
                if (null == tabFragmentSparseArray.get(position)) {
                    ProjectPagerFragment fragment = new ProjectPagerFragment().newInstance(bundle);
                    return fragment;
                } else {
                    ProjectPagerFragment fragment = (ProjectPagerFragment) tabFragmentSparseArray.get(position);
                    return fragment;
                }
            }

            @Override
            public int getCount() {
                return data.size();
            }

            /**
             * 预加载页面时调用
             * @param container
             * @param position
             * @return
             */
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                ProjectPagerFragment basePF = (ProjectPagerFragment) super.instantiateItem(container, position);
                tabFragmentSparseArray.put(position, basePF);
                return basePF;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                //tabFragmentSparseArray.remove(position);
                //super.destroyItem(container, position, object);
            }

        });

        //viewPager滑动监听
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            /**
             * 当某个页面被选中的时候回调这个方法
             * @param position 被选中页面的位置
             */
            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


}
